// index.js
// 获取应用实例
const app = getApp()

import user from '../../utils/user.js'
import {
    register,
    getSendVerifyCode,
    getCheckVerifyCode
} from '../../api/app.js'
import {
    dateFormat,
    anit,
    goToContract,
    getCardAge
} from '../../utils/util'
import {
    openSalaryCard,
    openSalaryVerify,
    querySalaryCard
} from '../../utils/salary-card.js'
Page({
    data: {
        verifyCode: '',
        code: '',
        codes: [],
        type: 0,
        oldPassword: '',
        newPassword: '',
        isCodes: false,
        countDownNum: 60, // 倒计时初始值为 60 秒
        countDownTimer: null, // 定时器标识符
        countingDown: false, // 是否正在倒计时的标志

        dataInformation: {
            id: '',
            userId: '',
            openId: '',
            userName: '', // 身份证姓名
            userHeadUrl: '',
            idCardNo: '', // 身份证号
            phone: '',
        },
        // 上一个页面传递过来的数据 这个页面要使用
        force: '',
        goRelation: '',
        idCardNo: '',
        isNeedAuthSalaryCard: '',
        relation: '',
        userName: '',
        showDialog: false,
        errorMsg: ''
    },
    async onLoad() {
        // await user.waitLogin()
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('dataFromBasic', (data) => {
            console.log(data, '上个页面传递过来的信息')
            this.setData({
                force: data.data.force,
                goRelation: data.data.goRelation,
                idCardNo: data.data.idCardNo,
                isNeedAuthSalaryCard: data.data.isNeedAuthSalaryCard,
                'dataInformation.phone': data.data.phone,
                'dataInformation.userName': data.data.userName,
                'dataInformation.idCardNo': data.data.idCardNo,
                relation: data.data.relation,
                userName: data.data.userName,
            })
            this.getSendVerifyCode()
        })


    },
    async onShow() {
        if (this.data.authenticateNumber && app.options.scene == 1038) {
            const queryResult = queryVerifyResult({
                authenticateNumber: this.data.authenticateNumber,
                companyId: app.globalData.companyId
            })
            if (queryResult.authenticateState === 'AUTHENTICATE_SUCCESS') {
                app.globalData.homePath = app.globalData.homePath + encodeURIComponent('&authenticateNumber=' + this.data.authenticateNumber)
                this.setData({
                    relation: true
                })
                this.register()
            }
            app.options = {}
        } else if (this.data.dataInformation.userName && this.data.goRelation) {
            console.log('开通微工卡 进入该判断')
            try {
                await querySalaryCard(app.globalData.companyId)
                this.setData({
                    relation: true
                })
                app.globalData.companyId = ''
                this.register()
            } catch (e) {
                await app.confirm('开通微工卡失败，是否暂时跳过？')
                this.setData({
                    goRelation: false
                })
                app.globalData.companyId = ''
                this.register()
            }
        }
    },
    onUnload() {
        this.stopCountDown()
    },
    // 获取验证码
    async getSendVerifyCode() {
        const nowYear = dateFormat('YYYY', new Date())
        const nowMonth = dateFormat('mm', new Date())
        await getSendVerifyCode({
            phone: Number(this.data.dataInformation.phone) + 1001010086 + ((Number(nowYear) + Number(nowMonth)) * 1000000)
        })
        await this.startCountDown()
    },
    // 验证码校验
    async getCheckVerifyCode() {
        await getCheckVerifyCode({
            phone: Number(this.data.dataInformation.phone),
            verifyCode: this.data.verifyCode
        })
        // 老注册流程搬过来 逻辑流程不变
        if (this.data.isNeedAuthSalaryCard && user.isOpenSalaryCard == 0 && (/type=0/.test(decodeURIComponent(app.globalData.homePath)) || /type=1/.test(decodeURIComponent(app.globalData.homePath)))) {
            console.log('强制开通微工卡')
            const result = await openSalaryCard(app.globalData.companyId, this.data.userName, this.data.idCardNo)
            this.setData({
                goRelation: result.subMchid
            })
        } else if (this.data.relation) {
            console.log('暂时不知道')
            this.register()
        } else {
            // 微保项目强制认证微工卡
            console.log(/type=4/.test(decodeURIComponent(app.globalData.homePath), /type=4/.test(decodeURIComponent(app.globalData.homePath))))
            if (/type=4/.test(decodeURIComponent(app.globalData.homePath))) {
                console.log('微保项目强制认证微工卡')
                const result = await openSalaryVerify(app.globalData.companyId, app.globalData.companyName, app.globalData.projectId, app.globalData.projectName, this.data.dataInformation.userName, this.data.idCardNo)
                this.setData({
                    goRelation: result.subMchid,
                    authenticateNumber: result.authenticateNumber
                })
            }
            // 国寿财项目强制跳过微工卡
            else if (/type=5/.test(decodeURIComponent(app.globalData.homePath))) {
                console.log('进入国寿财项目')
                this.setData({
                    goRelation: false
                })
                this.register()
            } else if (this.data.force === '0') {
                // 招聘二维码  标签没强制开通微工卡
                console.log('招聘二维码  标签没强制开通微工卡')
                this.register()
            } else {
                try {
                    const result = await querySalaryCard(app.globalData.companyId)
                    console.log(result, '第三个subMchid')
                    // 开通微工卡走的是这个逻辑
                    this.setData({
                        goRelation: result.subMchid
                    })
                    this.register()
                } catch (e) {
                    if (e) {
                        try {
                            await app.confirm('开通微工卡后即可提现到银行卡，是否立即绑定微工卡？', '去绑定', '暂不绑定')
                            const result = await openSalaryCard(app.globalData.companyId, this.data.dataInformation.userName, this.data.idCardNo)
                            console.log(result, '第四个goRelation')
                            // 扫完人脸后会走这个
                            this.setData({
                                goRelation: result.subMchid
                            })
                            console.log(this.data.goRelation)
                        } catch (e) {
                            this.setData({
                                goRelation: false
                            })
                            this.register()
                        }
                    } else {
                        this.setData({
                            goRelation: false
                        })
                        this.register()
                    }

                }


            }
        }

        // const eventChannel = this.getOpenerEventChannel()
        // eventChannel.emit('getNextPageCaptcha', {data: 'true'});
        // await wx.navigateBack()
    },

    async register() {
        this.data.dataInformation.openId = user.openid
        this.data.dataInformation.userHeadUrl = user.avatarUrl
        this.data.dataInformation.bankCardIs = 1
        this.data.dataInformation.userName = this.data.userName.replace(/\s*/g, '')
        this.data.dataInformation.isOpenSalaryCard = Number(this.data.goRelation)
        console.log(this.data.dataInformation, 'prevPage')
        const result = await register(this.data.dataInformation)

        if (result.code === 100) {
            this.setData({
                showDialog: true,
                errorMsg: result.msg
            })
            return
        }

        if (result === 'needPhoto') {
            app.toast('您的身份信息校验失败，请上传您的身份照片后重试')
            this.setData({
                isEdit: true
            })
            return
        }
        await user.reLogin()
        app.toast('注册成功，正在为您跳转...')
        if (/type=5/.test(decodeURIComponent(app.globalData.homePath)) && app.globalData.gscJoin) {
            app.globalData.gscJoin()
            return
        }
        setTimeout(() => {
            if (app.globalData.homePath) {
                wx.redirectTo({
                    url: '/pages/join/join',
                })
            } else if (app.globalData.registerBack) {
                wx.redirectTo({
                    url: app.globalData.registerBack,
                })
                app.globalData.registerBack = ''
            } else {
                wx.switchTab({
                    url: '/pages/index/index'
                })
            }
        }, 1000)
    },
    startCountDown: function () { // 开始倒计时
        if (this.data.countingDown) return // 如果正在倒计时，则直接返回

        this.setData({
            countingDown: true
        }) // 设置正在倒计时的标志

        let timer = setInterval(() => { // 每秒钟更新倒计时
            let newCountDownNum = this.data.countDownNum - 1
            if (newCountDownNum >= 0) { // 如果还未到 0 秒，则更新倒计时
                this.setData({
                    countDownNum: newCountDownNum
                })
            } else { // 如果已经到 0 秒，则取消定时器并重置倒计时
                clearInterval(this.data.countDownTimer)
                this.setData({
                    countDownNum: 60,
                    countingDown: false
                })
            }
        }, 1000)

        this.setData({
            countDownTimer: timer
        }) // 设置定时器标识符
    },
    stopCountDown: function () { // 停止倒计时
        clearInterval(this.data.countDownTimer) // 取消定时器
        this.setData({
            countDownNum: 60,
            countingDown: false
        }) // 重置倒计时和标志
    },
    // 输入密码
    inputNumber(event) {
        // 将密码分为多个字符
        this.setData({
            ['codes']: event.detail.value.split(''),
        })
        // 字符达到6个自动下一步
        if (event.detail.value.length === 6) {
            this.setData({
                verifyCode: event.detail.value.slice(0, 6)
            })
            this.getCheckVerifyCode()
        }
    },
    onCloseDialog() {
        this.setData({
            showDialog: false
        })
    },

    onToCustomerService() {
        wx.navigateTo({
            url: '/pages/service/service',
        })
    }
})